package com.travel.travel_springboot_web.controller;

import com.travel.travel_springboot_web.entity.Cart;
import com.travel.travel_springboot_web.entity.Order;
import com.travel.travel_springboot_web.service.CartService;
import com.travel.travel_springboot_web.utils.TokenUtil;
import com.travel.travel_springboot_web.utils.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/cart")
@CrossOrigin(
    originPatterns = {"http://localhost:*", "http://127.0.0.1:*"},
    methods = {
        RequestMethod.GET, 
        RequestMethod.POST, 
        RequestMethod.PUT, 
        RequestMethod.DELETE, 
        RequestMethod.OPTIONS
    },
    allowCredentials = "true"
)
public class CartController {
    
    private static final Logger logger = LoggerFactory.getLogger(CartController.class);
    
    @Autowired
    private CartService cartService;
    
    @Autowired
    private TokenUtil tokenUtil;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    @PostMapping("/add")
    public Map<String, Object> add(
            @RequestBody Cart cart,
            @RequestHeader(value = "Authorization", required = false) String authHeader) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 提取并验证token
            String token = tokenUtil.extractToken(authHeader);
            
            // 从token中获取用户ID
            Long userId = jwtUtil.getUserIdFromToken(token);
            logger.info("Adding to cart for user: {}", userId);
            
            if (userId == null) {
                throw new RuntimeException("请先登录");
            }
            
            // 验证参数
            if (cart.getGoodsId() == null) {
                throw new RuntimeException("商品ID不能为空");
            }
            if (cart.getNum() == null || cart.getNum() < 1) {
                throw new RuntimeException("商品数量必须大于0");
            }
            
            // 调用服务添加到购物车
            boolean success = cartService.addToCart(userId, cart.getGoodsId(), cart.getNum());
            
            if (success) {
                result.put("code", 200);
                result.put("message", "success");
            } else {
                result.put("code", 500);
                result.put("message", "添加购物车失败");
            }
        } catch (Exception e) {
            logger.error("Failed to add to cart: ", e);
            result.put("code", e.getMessage().contains("请先登录") ? 401 : 500);
            result.put("message", e.getMessage());
        }
        return result;
    }
    
    @GetMapping("/list")
    public Map<String, Object> list(@RequestHeader(value = "Authorization", required = false) String authHeader) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 提取并验证token
            String token = tokenUtil.extractToken(authHeader);
            
            // 从token中获取用户ID
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            Map<String, Object> cartData = cartService.getCartList(userId);
            result.put("code", 200);
            result.put("message", "success");
            result.put("data", cartData);
        } catch (Exception e) {
            logger.error("Failed to get cart list: ", e);
            result.put("code", e.getMessage().contains("请先登录") ? 401 : 500);
            result.put("message", e.getMessage());
        }
        return result;
    }
    
    @PutMapping("/{id}/num")
    public Map<String, Object> updateNum(@PathVariable Long id, @RequestParam Integer num,
                                       @RequestHeader(value = "Authorization", required = false) String authHeader) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 提取并验证token
            String token = tokenUtil.extractToken(authHeader);
            
            // 从token中获取用户ID
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            boolean success = cartService.updateNum(id, userId, num);
            if (success) {
                result.put("code", 200);
                result.put("message", "success");
            } else {
                result.put("code", 404);
                result.put("message", "Cart not found");
            }
        } catch (Exception e) {
            logger.error("Failed to update cart num: ", e);
            result.put("code", e.getMessage().contains("请先登录") ? 401 : 500);
            result.put("message", e.getMessage());
        }
        return result;
    }
    
    @PutMapping("/{id}/selected")
    public Map<String, Object> updateSelected(@PathVariable Long id, @RequestParam Integer selected,
                                            @RequestHeader(value = "Authorization", required = false) String authHeader) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 提取并验证token
            String token = tokenUtil.extractToken(authHeader);
            
            // 从token中获取用户ID
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            boolean success = cartService.updateSelected(id, userId, selected);
            if (success) {
                result.put("code", 200);
                result.put("message", "success");
            } else {
                result.put("code", 404);
                result.put("message", "Cart not found");
            }
        } catch (Exception e) {
            logger.error("Failed to update cart selected: ", e);
            result.put("code", e.getMessage().contains("请先登录") ? 401 : 500);
            result.put("message", e.getMessage());
        }
        return result;
    }
    
    @DeleteMapping("/{id}")
    public Map<String, Object> delete(@PathVariable Long id,
                                    @RequestHeader(value = "Authorization", required = false) String authHeader) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 提取并验证token
            String token = tokenUtil.extractToken(authHeader);
            
            // 从token中获取用户ID
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            boolean success = cartService.deleteCart(id, userId);
            if (success) {
                result.put("code", 200);
                result.put("message", "success");
            } else {
                result.put("code", 404);
                result.put("message", "Cart not found");
            }
        } catch (Exception e) {
            logger.error("Failed to delete cart: ", e);
            result.put("code", e.getMessage().contains("请先登录") ? 401 : 500);
            result.put("message", e.getMessage());
        }
        return result;
    }
    
    @PostMapping("/checkout")
    public Map<String, Object> checkout(@RequestHeader(value = "Authorization", required = false) String authHeader) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 提取并验证token
            String token = tokenUtil.extractToken(authHeader);
            
            // 从token中获取用户ID
            Long userId = jwtUtil.getUserIdFromToken(token);
            logger.info("Current userId from token: {}", userId);
            
            if (userId == null) {
                throw new RuntimeException("请先登录");
            }
            
            // 创建订单（不再需要传入地址ID）
            Order order = cartService.checkout(userId);
            
            result.put("code", 200);
            result.put("message", "success");
            result.put("data", order);
        } catch (Exception e) {
            logger.error("Failed to checkout: ", e);
            result.put("code", e.getMessage().contains("请先登录") ? 401 : 500);
            result.put("message", e.getMessage());
        }
        return result;
    }
} 